InstrumentType = new Object();

InstrumentType.getSearchBar = function() {

	Ext.define('NewInsInstrumentType', {
		extend : 'Ext.data.Model',
		fields : [
		          {	name : 'id',					type : 'int'		},
		          {	name : 'instrumentName',		type : 'string'		},
		          {	name : 'istrumentType',			type : 'int'		},
		          {	name : 'scripts',				type : 'int'		},
		          {	name : 'denominals',			type : 'int'		},
		          {	name : 'listed',				type : 'int'		},
		          {	name : 'withholdingTax',		type : 'string'		},
		          {	name : 'interestRate',			type : 'string'		},
		          {	name : 'interestType',			type : 'string'		},
		          {	name : 'dayBasis',				type : 'string'		},
		          {	name : 'couponAvailability',	type : 'int'		},
		          {	name : 'cuponFrequency',		type : 'int'		},
		          {	name : 'shortMaturable',		type : 'int'		},
		          {	name : 'calculationInput',		type : 'int'		}
		         ]
	});

	var instrumentTypeStore = new Ext.data.Store({
		model : 'NewInsInstrumentType',
	});

	return Ext.create('Ext.form.FieldContainer', {
		items : [ {
			xtype : 'triggerfield',
			triggerCls : 'x-form-search-trigger',
			id : 'newInsTypeTrigField',
			anchor : '36%',
			style : 'float:right;',
			emptyText : 'Search Instrument Type',
			listeners : {
				specialkey : function(field, e) {
					if (e.getKey() == e.ENTER) {
						Ext.Msg.alert('HI', 'Press Enter');
						var trigField = Ext.ComponentQuery.query('#newInsTypeTrigField')[0];
						trigField.fireEvent('onTriggerClick');
					}
				}
			},
			onTriggerClick : function() {
				var newInsTypeTrigField = Ext.ComponentQuery.query('#newInsTypeTrigField')[0];
				Ext.Ajax.request({
					url : 'getInstrumentTypes.action',
					params : {
						querry : newInsTypeTrigField.getValue()
					},
					success : function(response) {
						var obj = Ext.decode(response.responseText);
						instrumentTypeStore.loadRawData(obj.instrumentTypeList);
					}
				});

				var resultWindow = Ext.create('Ext.grid.Panel', {
					defaults : {
						anchor : '100%'
					},
					store : instrumentTypeStore,
					columns : [ {
						text : 'ID',
						dataIndex : 'id',
						flex : 1
					}, {
						text : 'Name',
						dataIndex : 'instrumentName',
						flex : 3
					} ],
					listeners : {
						itemdblclick : function(view, rec, item, index, eventObj) {
							var formPanl = Ext.ComponentQuery.query('#newInsTypeFormPanel')[0];
							/*formPanl.getForm().applyToFields({
								disabled : true
							});*/
							formPanl.getForm().loadRecord(rec);
							if(true==false){ //only viewing permissions
							formPanl.getForm().applyToFields({
								disabled : true
							});
							}
							Ext.getCmp('newInsTypeUpdateBtn').setVisible(true);
							Ext.getCmp('newInsTypeSaveBtn').setVisible(false);
							this.up('.window').close();
							Ext.ComponentQuery.query('#newInsTypeTrigField')[0].enable();
							var couponFr = Ext.ComponentQuery.query('#couponFreq')[0];
							if(rec.get("couponAvailability")===1){
								couponFr.enable();
							}else{
								couponFr.disable();
							}							
						}
					}
				});

				Ext.create('Ext.window.Window', {
					title : 'Search Results',
					height : 300,
					frame : true,
					width : 400,
					constrain : true,
					resizable : false,
					modal : true,
					layout : {
						type : 'fit'
					},
					items : [ resultWindow ]
				}).show();
			}
		} ]
	});
};

InstrumentType.getFieldSet1 = function() {
	return Ext.create('Ext.form.FieldSet', {
		title : 'Basic',
		defaults : {
			anchor : '100%'
		},
		items : [ {
			xtype : 'textfield',
			name : 'instrumentName',
			fieldLabel : 'Name',
			id : 'newInsTypeName',
			allowBlank : false,
			labelWidth : 60,
			blankText : 'Name cannot be null',
			emptyText : 'Name of the New Intrument Type',
			maxLength : 80,
			style : 'margin-left:5px',
			maxLengthText : 'Name is too long. Maximum 80 characters allowed!',
			msgTarget : 'under',
			listeners : {
				blur : function() {
					var insName = this.value;
					if(insName.trim()===''){
						Ext.ComponentQuery.query('#newInsTypeValidLbl')[0].setText('Name is Invalid!');
						Ext.ComponentQuery.query('#newInsTypeName')[0].reset();
					}else{
						Ext.Ajax.request({
							url : 'validInsTypeCode.action',
							params : {
								querry : insName,
							},
							success : function(response) {
								var obj = Ext.decode(response.responseText);
								if(obj.success){
									Ext.ComponentQuery.query('#newInsTypeValidLbl')[0].setText(insName+' is Already Used!');
									Ext.ComponentQuery.query('#newInsTypeName')[0].reset();
								}else{
									Ext.ComponentQuery.query('#newInsTypeValidLbl')[0].setText(insName+' is OK');
								}
							},
							failure : function(response){
								Ext.ComponentQuery.query('#newInsTypeValidLbl')[0].setText('Instrument Name Validation Failed!');
								this.reset();
							}
						});
					}
				},
			}
		},
		{
	 		xtype : 'label',
	 		id : 'newInsTypeValidLbl',
	 		text : '',
	    },
		{
			xtype : 'fieldcontainer',
			layout : 'hbox',
			style : 'margin-top:10px',
			items : [ {
				xtype : 'checkboxfield',
				boxLabel : 'Listed Instrument',
				name : 'listed',
				inputValue : 1,
				flex : 1,
				padding : '0 10 0 10',
			}, {
				xtype : 'checkboxfield',
				boxLabel : 'Short Matuarable',
				name : 'shortMaturable',
				flex : 1,
				inputValue : 1,
				padding : '0 10 0 0',
			} ]
		}, {
			xtype : 'fieldcontainer',
			layout : 'hbox',
			style : 'margin-top:10px',
			items : [ {
				xtype : 'checkboxfield',
				boxLabel : 'Script Availability',
				name : 'scripts',
				inputValue : 1,
				flex : 1,
				padding : '0 10 0 10',
			}, {
				xtype : 'checkboxfield',
				boxLabel : 'Government',
				name : 'istrumentType',
				flex : 1,
				inputValue : 1,
				padding : '0 10 0 0',
			} ]
		}, {
			xtype : 'checkboxfield',
			boxLabel : 'Denominals',
			name : 'denominals',
			inputValue : 1,
			id : 'newInsTypedenominal',
			disabled : false,
			padding : '0 10 0 10',
			style : 'margin-top:10px',
		} ]

	});
};

InstrumentType.getFieldSet2 = function() {
	return Ext.create('Ext.form.FieldSet', {
		title : 'Interest Calculation Parameters',
		defaults : {
			anchor : '100%'
		},
		items : [ {
			xtype : 'fieldcontainer',
			layout : 'hbox',
			items : [ new Ext.form.ComboBox({
				store : new Ext.data.Store({
					fields : [ 'wht' ],
					data : [ {
						"wht" : "No"
					}, {
						"wht" : "Upfront"
					}, {
						"wht" : "Maturity"
					}, {
						"wht" : "Vary"
					} ]
				}),
				displayField : 'wht',
				valueField : 'wht',
				labelWidth : 120,
				name : 'withholdingTax',
				value : 'No',
				flex : 1,
				padding : '0 10 0 0',
				editable : false,
				fieldLabel : 'Withholding Tax',
				emptyText : 'Fixed/Floating',
				applyTo : 'local-states',
			}), new Ext.form.ComboBox({
				store : new Ext.data.Store({
					fields : [ 'interest' ],
					data : [ {
						"interest" : "Fixed"
					}, {
						"interest" : "Floating"
					} ]
				}),
				displayField : 'interest',
				valueField : 'interest',
				fieldLabel : 'Interest Rate',
				name : 'interestRate',
				editable : false,
				flex : 1,
				value : 'Fixed',
				labelWidth : 120,
				applyTo : 'local-states',
				listeners : {
					select : function(combo, record, index) {
						if (combo.getValue() == 'Fixed') {
							var coupon = Ext.ComponentQuery.query('#newInsTypeCoupon')[0];
							coupon.setValue(0);
							coupon.enable();
						} else if (combo.getValue() == 'Floating') {
							var coupon = Ext.ComponentQuery.query('#newInsTypeCoupon')[0];
							coupon.disable();
							var couponFr = Ext.ComponentQuery.query('#couponFreq')[0];
							couponFr.disable();
						}
					}
				}
			}) ]
		}, {
			xtype : 'fieldcontainer',
			layout : 'hbox',
			items : [ new Ext.form.ComboBox({
				store : new Ext.data.Store({
					fields : [ 'interestCal' ],
					data : [ {
						"interestCal" : "Straight"
					}, {
						"interestCal" : "Discounted"
					} ]
				}),
				displayField : 'interestCal',
				valueField : 'interestCal',
				name : 'interestType',
				flex : 1,
				padding : '0 10 0 0',
				editable : false,
				value : 'Straight',
				labelWidth : 120,
				fieldLabel : 'Interest Calculation',
				style : 'margin-top:10px;',
			}), new Ext.form.ComboBox({
				store : new Ext.data.Store({
					fields : [ 'dayBasis' ],
					data : [ {
						"dayBasis" : "Act / Act"
					}, {
						"dayBasis" : "Act / 360"
					}, {
						"dayBasis" : "Act / 364"
					}, {
						"dayBasis" : "Act / 365"
					}, {
						"dayBasis" : "30 / 360"
					}, {
						"dayBasis" : "30 / 365"
					}, {
						"dayBasis" : "Vary"
					} ]
				}),
				displayField : 'dayBasis',
				valueField : 'dayBasis',
				name : 'dayBasis',
				labelWidth : 120,
				value : 'Act / 365',
				flex : 1,
				fieldLabel : 'Day Basis',
				selectOnFocus : true,
				style : 'margin-top:10px;',
			}) ]
		}, {
			xtype : 'fieldcontainer',
			layout : 'hbox',
			items : [ new Ext.form.ComboBox({
				store : new Ext.data.Store({
					fields : [ 'coupon', 'value' ],
					data : [ {
						'coupon' : "No",
						'value' : 0
					}, {
						'coupon' : "Available: Fixed Dates",
						'value' : 1
					}, {
						'coupon' : "Available: Varying Dates",
						'value' : 2
					} ]
				}),
				displayField : 'coupon',
				name : 'couponAvailability',
				id : 'newInsTypeCoupon',
				valueField : 'value',
				labelWidth : 120,
				fieldLabel : 'Coupon Availability',
				flex : 1,
				padding : '0 10 0 0',
				editable : false,
				style : 'margin-top:10px;',
				value : 0,
				listeners : {
					select : function(combo, record, index) {
						if (combo.getValue() == 1) {
							var couponFr = Ext.ComponentQuery.query('#couponFreq')[0];
							couponFr.enable();
						} else if (combo.getValue() == 0 || combo.getValue() == 2) {
							var couponFr = Ext.ComponentQuery.query('#couponFreq')[0];
							couponFr.disable();
							couponFr.reset();
						}
					}
				}
			}), {
				xtype : 'numberfield',
				value : 0,
				minValue:1,
				id : 'couponFreq',
				name : 'cuponFrequency',
				disabled : true,
				labelWidth : 120,
				flex : 1,
				fieldLabel : 'Coupon Frequency',
				style : 'margin-top:10px;',
				listeners : {
					   render: function(p) {
							var theElem = p.getEl();
							var theTip = Ext.create('Ext.tip.Tip', {
								html: 'Coupon Frequency in Months',
								margin: '20px 0 0 0',
								shadow: false
							});						   
							p.getEl().on('mouseover', function(){
								theTip.showAt(theElem.getX(), theElem.getY());
							});						   
							p.getEl().on('mouseleave', function(){
								theTip.hide();
							});
						}
					}
			} ]
		},		
		{
			xtype : 'fieldcontainer',
			layout:'anchor',
			items : [
			    {
			    	xtype : 'combo',
			    	anchor: '50%',
			    	editable : false,
			 		store : new Ext.data.Store({
			 			fields : [ 'input', 'value' ],
			 			data : [ {
			 				'input' : 'Deal Value', 'value' : 1
			 			}, {
			 				'input' : 'Maturity Value', 'value' : 2
			 			}
			 			]
			 		}),
			 		displayField : 'input',
			 		valueField : 'value',
			 		name : 'calculationInput',
			 		labelWidth : 120,
			 		value : 1,
			 		padding : '0 5 0 0',
			 		fieldLabel : 'Input Value',
			 		style : 'margin-top:10px;',
			 		listeners : {
						   render: function(p) {
								var theElem = p.getEl();
								var theTip = Ext.create('Ext.tip.Tip', {
									html: 'Input Value for the Calculations',
									margin: '20px 0 0 0',
									shadow: false
								});						   
								p.getEl().on('mouseover', function(){
									theTip.showAt(theElem.getX(), theElem.getY());
								});						   
								p.getEl().on('mouseleave', function(){
									theTip.hide();
								});
							}
						}
			    }
			    ]
		}

		]

	});
};

InstrumentType.getCenterPanel = function() {
	var searchBar = InstrumentType.getSearchBar();
	var filedset1 = InstrumentType.getFieldSet1();
	var filedset2 = InstrumentType.getFieldSet2();

	return Ext.create('Ext.form.FormPanel', {
		title : 'Defining New Instrument Type',
		id : 'newInsTypeFormPanel',
		bodyPadding : 20,
		autoScroll : true,
		frame : true,
		defaults : {
			labelWidth : 110,
			anchor : '65%',
		},
		fieldDefaults : {
			labelAlign : 'left'
		},
		items : [ searchBar, filedset1, filedset2 ],
		buttonAlign : 'center',
		buttons : [ {
			text : 'Cancel',
			handler : function() {
				App.Core.removeScreen();
				Ext.getCmp('newInsTypeUpdateBtn').setVisible(false);
				Ext.getCmp('newInsTypeSaveBtn').setVisible(true);
			}
		}, {
			text : 'Reset',
			handler : function() {
				this.up('form').getForm().reset();
				this.up('form').getForm().applyToFields({
					disabled : false
				});
				Ext.getCmp('newInsTypeUpdateBtn').setVisible(false);
				Ext.getCmp('newInsTypeSaveBtn').setVisible(true);
				Ext.ComponentQuery.query('#newInsTypeValidLbl')[0].setText('');
			}
		}, {
			text : 'Save',
			id:'newInsTypeSaveBtn',
			itemId : 'saveButton',
			handler : function() {
				var form = this.up('form').getForm();
				form.url = 'addNewInsType.action';
				if (form.isValid()) {
					form.submit({
						success : function(form, action) {
							form.reset();
							var couponFr = Ext.ComponentQuery.query('#couponFreq')[0];
							couponFr.disable();
							Ext.Msg.alert('Success', 'New Instrument Type created <br> Reference Id: ' + action.result.id);
						},
						failure : function(form, action) {
							Ext.Msg.alert('Failed', 'There is some error returned from the server.');
						}
					});
				}
			}
		},
		{
			text : 'Update',
			itemId : 'updateButton',
			id:'newInsTypeUpdateBtn',
			hidden : true,
			handler : function() {
				var form = this.up('form').getForm();
				form.url = 'modifyInsType.action';
				if (form.isValid()) {
					form.submit({
						success : function(form, action) {
							form.reset();
							Ext.getCmp('newInsTypeUpdateBtn').setVisible(false);
							Ext.getCmp('newInsTypeSaveBtn').setVisible(true);
							var couponFr = Ext.ComponentQuery.query('#couponFreq')[0];
							couponFr.disable();
							Ext.Msg.alert('Success', action.result.instrumentName+' Instrument Type Updated.');
						},
						failure : function(form, action) {
							Ext.Msg.alert('Failed', 'Error returned from the server.');
						}
					});
				}
			}
		}]
	});
};
